'use client';

import { useEffect, useState } from "react";
import { Divider, Spin, Tag, Space } from "antd";
import { CaretDownOutlined, CaretUpOutlined } from "@ant-design/icons";
import { API_NAME, MOCK_LABEL_LIST } from "../../constant";
import "./index.css";

const { CheckableTag } = Tag;
const MAX_COUNT = 4;

interface LabelListProps {
    primaryId: string;
    onChangeLabels: (selectedLabels: {categoryId: string; labelIds: string[]}[]) => void;
}

export default function LabelList({ primaryId, onChangeLabels }: LabelListProps) {
    const [spinning, setSpinning] = useState(false);
    const [categoryAndLabelList, setCategoryAndLabelList] = useState<any[]>([]);
    const [isPutAway, setIsPutAway] = useState(true);
    const [selectedLabels, setSelectedLabels] = useState<Record<string, string[]>>({});

    const getCategoryAndLabel = async () => {
        setSpinning(true);
        try {
            // 暂时使用模拟数据
            const data = MOCK_LABEL_LIST;
            
            if (data?.length > 0) {
                const filterData = data.filter(
                    (item: any) => item?.labelDTOList?.length > 0
                );
                setCategoryAndLabelList(filterData);
                
                // 初始化选中状态
                const initialSelected: Record<string, string[]> = {};
                filterData.forEach(category => {
                    initialSelected[category.id] = [];
                });
                setSelectedLabels(initialSelected);
            } else {
                setCategoryAndLabelList([]);
                setSelectedLabels({});
            }
        } catch (err) {
            console.error(err);
        } finally {
            setSpinning(false);
        }
    };

    const onChangePutAway = () => {
        setIsPutAway(!isPutAway);
    };

    const handleLabelChange = (categoryId: string, labelId: string, checked: boolean) => {
        setSelectedLabels(prev => {
            const newSelected = {...prev};
            
            if (checked) {
                // 添加选中
                if (!newSelected[categoryId]) {
                    newSelected[categoryId] = [];
                }
                if (!newSelected[categoryId].includes(labelId)) {
                    newSelected[categoryId] = [...newSelected[categoryId], labelId];
                }
            } else {
                // 移除选中
                if (newSelected[categoryId]) {
                    newSelected[categoryId] = newSelected[categoryId].filter(id => id !== labelId);
                }
            }
            
            // 通知父组件
            const selected = Object.entries(newSelected)
                .filter(([_, labelIds]) => labelIds.length > 0)
                .map(([categoryId, labelIds]) => ({ categoryId, labelIds }));
            
            onChangeLabels(selected);
            
            return newSelected;
        });
    };

    useEffect(() => {
        if (primaryId) {
            getCategoryAndLabel();
        }
    }, [primaryId]);

    return (
        <Spin spinning={spinning}>
            <div className="label-list-box">
                {categoryAndLabelList.map((categoryItem, index) => (
                    <div
                        className="label-list-item"
                        key={categoryItem.id}
                        style={{
                            display: index >= MAX_COUNT && isPutAway ? "none" : "block",
                            marginBottom: 16
                        }}
                    >
                        <div className="label-category-title">
                            {categoryItem.categoryName}:
                        </div>
                        <Space size={[8, 8]} wrap className="label-tags">
                            {categoryItem.labelDTOList.map((labelItem: any) => (
                                <CheckableTag
                                    key={labelItem.id}
                                    checked={selectedLabels[categoryItem.id]?.includes(labelItem.id) || false}
                                    className="label-tag"
                                    onChange={(checked) => 
                                        handleLabelChange(categoryItem.id, labelItem.id, checked)
                                    }
                                >
                                    {labelItem.labelName}
                                </CheckableTag>
                            ))}
                        </Space>
                    </div>
                ))}
                {categoryAndLabelList.length > MAX_COUNT && (
                    <Divider
                        onClick={onChangePutAway}
                        dashed
                        style={{
                            marginTop: 10,
                            marginBottom: 10,
                            fontSize: 13,
                            cursor: "pointer",
                        }}
                    >
                        {isPutAway ? "展开" : "收起"}
                        {isPutAway ? (
                            <CaretDownOutlined style={{ marginLeft: 4 }} />
                        ) : (
                            <CaretUpOutlined style={{ marginLeft: 4 }} />
                        )}
                    </Divider>
                )}
            </div>
        </Spin>
    );
}